// 文件名: TdtMixin.js

import { address, history, newLocation, stopTime } from '@/api/gps'
import { getVehiclesListNoLogin } from '@/api/vehicleService'
import {
  Toast as VantToast
} from 'vant'

export default {
  data() {
    return {
      map: null,
      mapRef: 'mapContent',
      T: null,
      vehiclesList: [],
      vehicleId: null,
      companyId: null,
      token: null,
      currentVehicle: null,
      carIcon: 'https://obs-user-test.obs.cn-east-3.myhuaweicloud.com:443/pictures/test_1753672404_aImt0o3Jg7.png',
      carOverlay: null,
      vehicleMarkerClick: false,
      defaultLonLat: [121.9353166667, 29.907515],
      stayPositionList: [],
      historyData: [],
      _CarTrack: null,
      markers: [],
      currentStayPoint: null,
      stayMarkerClick: false,
      mileage: 0,
      authInfo: null
    }
  },

  created() {
    this.T = window.T

    this.vehicleId = this.$route.query.vehicleId
      ? parseInt(this.$route.query.vehicleId) : null

    this.companyId = this.$route.query.companyId
      ? parseInt(this.$route.query.companyId) : null

    this.token = this.$route.query.token

    this.authInfo = {
      token: this.token,
      companyId: this.companyId
    }
  },

  methods: {
    async init() {
      // 修复点 1: 仅初始化地图
      this.map = new this.T.Map(this.mapRef, {
        projection: 'EPSG:900913'
      })
      this.setCenterAndZoom(this.defaultLonLat[0], this.defaultLonLat[1], 18)
    },

    async setCarMarker(vehicleInfo, options = {}) {
      const vehicleId = vehicleInfo.id
      const res = await newLocation({
        'id': vehicleId
      }, this.authInfo)

      // 修复点 2: 遇到 GPS 为空时，使用 console.warn 和 return
      if (!res.data[0]) {
        console.warn(`[GPS ERROR] 车辆 ID:${vehicleId} (${vehicleInfo.licenseNumber || 'N/A'}) 暂无位置信息，跳过标记设置。`)
        return
      }

      const vehicle = vehicleInfo

      vehicle.lastGps = res.data[0]
      const lon = vehicle.lastGps.lastLon
      const lat = vehicle.lastGps.lastLat
      const degree = vehicle.lastGps.lastCourse || 0

      vehicle.address = await this.getAddressByLonLat(lon, lat)

      const defaultOptions = {
        width: 41,
        height: 22,
        iconUrl: this.carIcon,
        ...options
      }

      const initialLngLat = new this.T.LngLat(lon, lat)

      const carOverlay = new this.T.CarOverlay(initialLngLat, defaultOptions)
      this.map.addOverLay(carOverlay)
      carOverlay.setRotate(degree - 90)
      carOverlay.img.addEventListener('click', () => {
        this.currentVehicle = vehicle
        this.vehicleMarkerClick = true
      })

      carOverlay.id = vehicleId

      this.markers.push(carOverlay)
    },

    async getVehiclesList() {
      try {
        const res = await getVehiclesListNoLogin(
          { 'gps': true },
          this.companyId
        )
        const car = res.data.car
        const gps = res.data.gps

        const vehiclesMap = new Map(gps.map(item => [item.imei, item]))

        const vehicles = car.map(item => {
          return {
            ...item,
            gps: vehiclesMap.get(item.imei)
          }
        }).filter(item => item.type.type !== 'noDriver')

        return vehicles
      } catch (error) {
        VantToast.fail(error.message || '车辆列表获取失败')
        return []
      }
    },

    async getAddressByLonLat(lon, lat) {
      const res = await address({ 'lat': lat, 'lon': lon }, this.authInfo)
      return res.data.formatted_address
    },

    setCenterAndZoom(lon, lat, zoom) {
      this.map.centerAndZoom(new this.T.LngLat(lon, lat), zoom)
    },

    getCurrentVehicle(vehicles) {
      if (this.vehicleId) {
        return vehicles.find(item => item.id === this.vehicleId)
      } else {
        return vehicles.filter(item => item.imei)?.[0]
      }
    },

    checkResize() {
      setTimeout(() => {
        this.map.checkResize()
      }, 300)
    },

    async queryHistory(params) {
      VantToast.loading({
        message: '加载中...',
        forbidClick: true
      })
      try {
        this.clearMarker()
        this.clearCustomMarker()
        this.clearTrack()
        const historys = await history(params, this.authInfo)
        const stayPoints = await stopTime(params, this.authInfo)
        if (!stayPoints.data?.records || stayPoints.data.records.length <= 0) {
          return VantToast('当前暂无行历史轨迹')
        }

        this.stayPositionList = stayPoints.data.records.reverse()

        this.setStayPointsToMap()

        if (historys.data.length) {
          this.historyData = historys.data
          const start = historys.data[0].mileage
          const end = historys.data[historys.data.length - 1].mileage
          this.mileage = end - start
          this.drawTracks()
        }
        VantToast.clear()
        this.currentStayPoint = this.stayPositionList[0]
      } catch (error) {
        console.log('error --------->', error)
        VantToast.clear()
        VantToast('历史轨迹查询失败')
      }
    },

    setStayPointsToMap() {
      this.stayPositionList.forEach((item, index) => {
        const marker = new this.T.Marker(new this.T.LngLat(item.lon, item.lat))
        item.index = index
        marker.id = item.id

        this.map.addOverLay(marker)

        marker.addEventListener('click', () => {
          this.currentStayPoint = item
          this.stayMarkerClick = true
        })

        item.marker = marker
      })
    },

    drawTracks() {
      const arr = this.historyData.map(element => {
        return new this.T.LngLat(element.lon, element.lat)
      })

      this.map.setViewport(arr)

      this._CarTrack = new this.T.CarTrack(this.map, {
        interval: 5,
        speed: 1,
        dynamicLine: true,
        polylinestyle: { color: '#2C64A7', weight: 10, opacity: 0.9 },
        Datas: arr,
        passOneNode: this.passOneNode,
        carstyle: {
          iconUrl: 'https://obs-user-test.obs.cn-east-3.myhuaweicloud.com:443/pictures/test_1753672404_aImt0o3Jg7.png'
        }
      })
    },

    clearTrack() {
      if (this._CarTrack) {
        this._CarTrack.clear()
      }
    },

    clearMarker() {
      // 注意：TdtMixin 中的 clearOverLays 会清除所有覆盖物，包括汽车标记和历史轨迹
      if (this.map) {
        this.map.clearOverLays()
        this.markers = [] // 确保数组也清空
      }
    },

    clearCustomMarker() {
      // 这里的 markers 应该包含所有车辆的 CarOverlay 实例
      this.markers.forEach(item => {
        this.map.removeOverLay(item)
      })

      this.markers = []
    },

    getMapZoom() {
      if (!this.map) return 18

      return this.map.getZoom()
    }
  }
}

// import { getVehiclesList, getVehiclesListNoLogin } from '@/api/vehicleService'
// import { address, history, newLocation, stopTime } from '@/api/gps'
// import {
//   Toast as VantToast
// } from 'vant'
// export default {
//   data() {
//     return {
//       map: null,
//       mapRef: 'mapContent',
//       T: null,
//       vehiclesList: [],
//       vehicleId: null,
//       companyId: null,
//       token: null,
//       currentVehicle: null,
//       carIcon: 'https://obs-user-test.obs.cn-east-3.myhuaweicloud.com:443/pictures/test_1753672404_aImt0o3Jg7.png',
//       carOverlay: null,
//       vehicleMarkerClick: false,
//       defaultLonLat: [121.9353166667, 29.907515],
//       stayPositionList: [],
//       historyData: [],
//       _CarTrack: null,
//       markers: [],
//       currentStayPoint: null,
//       stayMarkerClick: false,
//       mileage: 0,
//       authInfo: null
//     }
//   },

//   created() {
//     this.T = window.T

//     this.vehicleId = this.$route.query.vehicleId
//       ? parseInt(this.$route.query.vehicleId) : null

//     this.companyId = this.$route.query.companyId
//       ? parseInt(this.$route.query.companyId) : null

//     this.token = this.$route.query.token

//     this.authInfo = {
//       token: this.token,
//       companyId: this.companyId
//     }
//   },

//   methods: {
//     async init() {
//       this.map = new this.T.Map(this.mapRef, {
//         projection: 'EPSG:900913'
//       })

//       this.setCenterAndZoom(this.defaultLonLat[0], this.defaultLonLat[1], 18)

//       const vehicles = await this.getVehiclesList()
//       for (let i = 0; i < vehicles.length; i++) {
//         const vehicle = vehicles[i]
//         if (!vehicle?.imei) continue
//         await this.setCarMarker(vehicle, {})
//       }

//       this.vehiclesList = vehicles

//       this.currentVehicle = this.getCurrentVehicle(this.vehiclesList)

//       const lon = this.currentVehicle.lastGps.lastLon
//       const lat = this.currentVehicle.lastGps.lastLat
//       this.setCenterAndZoom(lon, lat, 18)
//     },

//     async setCarMarker(vehicleInfo, options = {}) {
//       const vehicleId = vehicleInfo.id
//       const res = await newLocation({
//         'id': vehicleId
//       }, this.authInfo)

//       if (!res.data[0]) {
//         return this.$message.error('暂无车辆位置信息，请稍后重试')
//       }

//       const vehicle = vehicleInfo

//       vehicle.lastGps = res.data[0]
//       const lon = vehicle.lastGps.lastLon
//       const lat = vehicle.lastGps.lastLat
//       const degree = vehicle.lastGps.lastCourse || 0

//       vehicle.address = await this.getAddressByLonLat(lon, lat)

//       const defaultOptions = {
//         width: 41,
//         height: 22,
//         iconUrl: this.carIcon,
//         ...options
//       }

//       const initialLngLat = new this.T.LngLat(lon, lat)

//       const carOverlay = new this.T.CarOverlay(initialLngLat, defaultOptions)
//       this.map.addOverLay(carOverlay)
//       carOverlay.setRotate(degree - 90)
//       carOverlay.img.addEventListener('click', () => {
//         this.currentVehicle = vehicle
//         this.vehicleMarkerClick = true
//       })

//       carOverlay.id = vehicleId

//       this.markers.push(carOverlay)
//     },

//     async getVehiclesList() {
//       try {
//         const res = await getVehiclesListNoLogin(
//           { 'gps': true },
//           this.companyId
//         )
//         const car = res.data.car
//         const gps = res.data.gps

//         const vehiclesMap = new Map(gps.map(item => [item.imei, item]))

//         const vehicles = car.map(item => {
//           return {
//             ...item,
//             gps: vehiclesMap.get(item.imei)
//           }
//         }).filter(item => item.type.type !== 'noDriver')

//         return vehicles
//       } catch (error) {
//         this.$message.error(error.message || '车辆列表获取失败')
//       }
//     },

//     async getAddressByLonLat(lon, lat) {
//       const res = await address({ 'lat': lat, 'lon': lon }, this.authInfo)

//       return res.data.formatted_address
//     },

//     setCenterAndZoom(lon, lat, zoom) {
//       this.map.centerAndZoom(new this.T.LngLat(lon, lat), zoom)
//     },

//     getCurrentVehicle(vehicles) {
//       if (this.vehicleId) {
//         return vehicles.find(item => item.id === this.vehicleId)
//       } else {
//         return vehicles.filter(item => item.imei)?.[0]
//       }
//     },

//     checkResize() {
//       setTimeout(() => {
//         this.map.checkResize()
//       }, 300)
//     },

//     async queryHistory(params) {
//       VantToast.loading({
//         message: '加载中...',
//         forbidClick: true
//       })
//       try {
//         this.clearMarker()
//         this.clearCustomMarker()
//         this.clearTrack()
//         const historys = await history(params, this.authInfo)
//         const stayPoints = await stopTime(params, this.authInfo)
//         if (!stayPoints.data?.records || stayPoints.data.records.length <= 0) {
//           return VantToast('当前暂无行历史轨迹')
//         }

//         this.stayPositionList = stayPoints.data.records.reverse()

//         this.setStayPointsToMap()

//         if (historys.data.length) {
//           this.historyData = historys.data
//           const start = historys.data[0].mileage
//           const end = historys.data[historys.data.length - 1].mileage
//           this.mileage = end - start
//           this.drawTracks()
//         }
//         VantToast.clear()
//         this.currentStayPoint = this.stayPositionList[0]
//       } catch (error) {
//         console.log('error --------->', error)
//         VantToast.clear()
//         VantToast('历史轨迹查询失败')
//       }
//     },

//     setStayPointsToMap() {
//       this.stayPositionList.forEach((item, index) => {
//         const marker = new this.T.Marker(new this.T.LngLat(item.lon, item.lat))
//         item.index = index
//         marker.id = item.id

//         this.map.addOverLay(marker)

//         marker.addEventListener('click', () => {
//           this.currentStayPoint = item
//           this.stayMarkerClick = true
//         })

//         item.marker = marker
//       })
//     },

//     drawTracks() {
//       const arr = this.historyData.map(element => {
//         return new this.T.LngLat(element.lon, element.lat)
//       })

//       this.map.setViewport(arr)

//       this._CarTrack = new this.T.CarTrack(this.map, {
//         interval: 5,
//         speed: 1,
//         dynamicLine: true,
//         polylinestyle: { color: '#2C64A7', weight: 10, opacity: 0.9 },
//         Datas: arr,
//         passOneNode: this.passOneNode,
//         carstyle: {
//           iconUrl: 'https://obs-user-test.obs.cn-east-3.myhuaweicloud.com:443/pictures/test_1753672404_aImt0o3Jg7.png'
//         }
//       })
//     },

//     clearTrack() {
//       if (this._CarTrack) {
//         this._CarTrack.clear()
//       }
//     },

//     clearMarker() {
//       if (this.map) {
//         this.map.clearOverLays()
//       }
//     },

//     clearCustomMarker() {
//       this.markers.forEach(item => {
//         this.map.removeOverLay(item)
//       })

//       this.markers = []
//     },

//     getMapZoom() {
//       if (!this.map) return 18

//       return this.map.getZoom()
//     }
//   }
// }
